/* Api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { getRichTextContent } from '@src/api/SystemApi';
/* enum */
import AuthEnum from '@model/enum/AuthEnum.ts';
import { TaskExceptionStateLabelEnum, TaskCreateMethodLabelEnum } from '@model/enum/LabelEnum.ts';
/* components */
import ConnectorTableDialog from "@src/modules/task/list/components/ConnectorTableDialog";
import LogisticsMixin from '@src/mixins/logisticsMixin'
import TaskCreateTimeDialog from './components/TaskCreateTimeDialog.vue';

/* enum */
import StorageModuleEnum from '@model/enum/StorageModuleEnum';
import { GrayFunctionEnum } from '@model/grayFunction';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

import { smoothLogisticsField } from '@service/LogisticsService'
/** model */
import TaskStateEnum from '@model/enum/TaskStateEnum.ts';
import { fields, AbnormalList, qualityFields, FaultLibrary } from './TaskFieldModel';

import { LINK_REG } from '@src/model/reg';

/** utils */
import Page from '@model/Page';
import { ctiCallOut } from '@src/util/ctisdk';
import { getRootWindow } from '@src/util/dom';
import { getAllGrayInfo } from '@src/util/grayInfo';
import { formatDate, isObject, isEmpty } from 'pub-bbx-utils';
import { storageGet, storageSet } from '@src/util/storage';
import { safeNewDate } from '@src/util/time';
import _, { debounce } from 'lodash';

import { pageTaskList } from 'pub-bbx-global/pageType/dist';
import AuthUtil from '@src/util/auth';
import StorageUtil from '@src/util/storage.ts';
import { sessionStorageGet, sessionStorageRemove } from '@src/util/storageV2';
import { getRootWindowInitData } from '@src/util/window'
/* service */
import { getFieldName, mergeFieldsWithProperty } from '@service/FieldService.ts';
import { formattedOpenDataTooltip } from '@service/OpenDataService.ts';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts';
import tourGuide from '@src/mixins/tourGuide';
import VersionMixin from '@src/mixins/versionMixin/index.ts';
import { isBasicEditionHideApi, isBasicEditionHideEvent, isBasicEditionHidePart, isBasicEditionHidePay, isBasicEditionHidePlanWork, isBasicEditionHidePrintTask, isBasicEditionHideProduct, isBasicEditionHideServe, isBasicEditionHideServiceReport, isShowBatchSendingServiceReports } from '@shb-lib/version';

import { isOpenData, openAccurateTab } from '@src/util/platform';

import { isCalendar } from '@src/util/CalendarUtil';

import AuthMixin from '@src/mixins/authMixin';

import i18n from '@src/locales'
import { formatAddress } from 'pub-bbx-utils';
const TASK_LIST_KEY = 'plantask_task_list';
const MAXCHECK = 500
// 列表筛选字段类型
const LIST_FILTER_FORM_TYPE = ['attachment', 'autograph'];

import { productSerialNumberFormat } from '@src/modules/contract/util/productFormat.js'
/* mixins */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'plantask-task-list',
  inject: ['initData'],
  mixins: [
    tourGuide, 
    VersionMixin, 
    ThemeMixin, 
    AuthMixin, 
    LogisticsMixin,
    VersionControlTaskMixin
  ],
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isOpenData,
      filterData: {}, // 状态数据
      planTimeType: '', // 判断计划时间展示的样式
      planStartTimeType: '', // 判断计划开始时间展示的样式
      planEndTimeType: '', // 判断计划完成时间展示的样式
      exportColumnList: [],
      columns: [],
      columnNum: 1,
      currentTaskType: {},
      loading: false,
      multipleSelection: [],
      multipleSelectionPanelShow: false,

      tableKey: (Math.random() * 1000) >> 2,
      taskStateEnum: TaskStateEnum,
      taskStatusFields: [
        'onceOverTime',
        'onceRefused',
        'oncePaused',
        'onceRollback',
        'onceReallot',
        'oncePrinted',
        'positionException',
        'source'
      ],
      taskTypes: [
        {
          name: i18n.t('common.base.all'),
          id: '',
        },
      ],
      taskFields: [],
      taskReceiptFields: [],
      taskPublicFields: [], // 公共字段
      taskCommonFields:[], // 公共字段
      taskPage: new Page(),
      totalItems: 0,
      navWidth: window.innerWidth - 120,
      abnormalData: {},
      abnormals: AbnormalList,
      taskCustomExceptionNodeList: [{englishName: 'all', exceptionName: i18n.t('common.base.all')}],
      exceptionNodes: 'all', // 选择异常
      isCalendar,
      isShowImportCost: false,
      tableContainerHeight:'440px',

      // collapse 状态栏折叠判断
      taskStateNeedCollapse: false, // 工单状态是否需要折叠
      taskStateCollapse: false, // 工单状态折叠
      taskTypeNeedCollapse: false, // 工单状态是否需要折叠
      taskTypeCollapse: false, // 工单类型折叠
      visualAngle: 'all', // 创建视角
      visualAngleList: [
        { label: i18n.t('common.base.all'), value: 'all' },
        { label: i18n.t('common.task.angle.create'), value: 'createUser' },
        { label: i18n.t('common.task.angle.execute'), value: 'executor' },
        { label: i18n.t('common.task.angle.synergy'), value: 'synergyId' },
      ],
      // 高级筛选条件
      conditionParams: {
        conditions: [],
        systemConditions: [],
      },
      // taskPage: [], // 工单列表
      taskState: 'all', // 工单状态列表 移到计算属性中 单选方案
      // 工单状态列表 checked 暂时无用，未来如果使用多选可以选用
      taskStates: [
        { label: i18n.t('common.base.all'), value: 'all', checked: true, },
        { label: TaskStateEnum.CREATED.name, value: TaskStateEnum.CREATED.value, checked: false, },
        { label: TaskStateEnum.ALLOCATED.name, value: TaskStateEnum.ALLOCATED.value, checked: false, },
        { label: TaskStateEnum.ACCEPTED.name, value: TaskStateEnum.ACCEPTED.value, checked: false, },
        { label: TaskStateEnum.PROCESSING.name, value: TaskStateEnum.PROCESSING.value, checked: false, },
        { label: TaskStateEnum.FINISHED.name, value: TaskStateEnum.FINISHED.value, checked: false, },
        { label: TaskStateEnum.EXCEPTION.name, value: TaskStateEnum.EXCEPTION.value, checked: false, },
        { label: TaskStateEnum.UNFINISHED.name, value: TaskStateEnum.UNFINISHED.value, checked: false, },
        { label: TaskStateEnum.OFFED.name, value: TaskStateEnum.OFFED.value, checked: false, },
        { label: TaskStateEnum.CLOSED.name, value: TaskStateEnum.CLOSED.value, checked: false, },
      ],
      sortModel: null, // 排序
      allGrayInfo:null,

      richtextVisible:false,
      richtextContent:null,
      preViews: [],
      provideType: '', // 服务商查询类型
      showViewportGuide: false, // 是否显示引导页
      // 工单列表统计字段
      createdTaskNumber: '',
      finishedTaskNumber: '',
      uncreatedTaskNumber: ''
    };
  },
  computed: {
    planId() {
      return this.shareData.task.id
    },
    // 工单类型id
    taskTypeId() {
      return this.shareData?.task?.task?.templateId
    },
    // 高级搜索customize-list
    searchCustomerList() {
      const allWithoutCommonFields = [...this.taskFields, ...this.taskReceiptFields].filter(item => !item.isCommon)
      return [...allWithoutCommonFields, ...this.taskCommonFields].sort((a, b) => a.orderId - b.orderId)
    },
    /** 公共字段 */
    commonFields(){
      return this.taskCommonFields.filter(item=>item.isCommon)
    },
    /** 是否显示归档工单按钮 */
    showGuidangBtn(){
      return this.taskState === TaskStateEnum.CLOSED.value && this.auth?.TASK_ARCHIVE === 3
    },
    /** 权限数据 */
    auth() {
      return this.initData.auth || {};
    },
    /** 获取是否开启联系人地址产品 */
    customerSetting() {
      let {
        address,
        product,
        linkman,
      } = this.currentTaskTypeCustomerFieldSetting;
      return {
        addressOn: address == true,
        productOn: product == true,
        linkmanOn: linkman == true,
      };
    },
    /** 当前工单类型客户字段设置 */
    currentTaskTypeCustomerFieldSetting() {
      let customerFields = this.taskFields.filter(
        (field) => field.formType == 'customer'
      );
      let customerField = customerFields[0];
      let customerSetting = {};

      if (customerField) {
        let setting = customerField.setting || {};
        customerSetting = setting.customerOption || {};
      }

      return customerSetting;
    },
    /** 判断呼叫中心开启电话 */
    callCenterModule() {
      return localStorage.getItem('call_center_module') && Number(localStorage.getItem('call_center_module'))
    },
    /** 导出权限 */
    exportPermission() {
      return this.canTaskImport || this.canTaskExport
    },
    canTaskImport() {
      return this.auth?.TASK_IMPORT && this.auth?.TASK_ADD
    },
    canTaskExport() {
      return this.auth?.TASK_EXPORT
    },
    // 转派条件
    exportPermissionTaskEdit() {
      return this.auth.TASK_EDIT === 3;
    },
    exportPermissionTaskBatchDispatch() {
      return this.auth.TASK_BATCH_DISPATCH === 3;
    },
    // 批量工单转派权限
    batchReallotPermission() {
      return this.auth.TASK_BATCH_REASSIGNMENT === 3;
    },
    // 批量打印工单权限
    batchPrintServiceReportPermission () {
      return this.auth.TASK_BATCH_PRINT === 3;
    },
    // 批量生成服务报告权限
    batchCreateServiceReportPermission () {
      return this.auth.TASK_BATCH_REPORT === 3;
    },
    /** 高级搜索面板宽度 */
    panelWidth() {
      return `${420 * this.columnNum}px`;
    },
    /** 查看工单全部权限 */
    permissionTaskView() {
      return this.globalIsHaveUserViewDetailAuth
      // return this.auth.TASK_VIEW === 3;
    },
    /** 当前选中的工单ids */
    selectedIds() {
      return this.multipleSelection.map((p) => p.id);
    },
    /** 服务项目 服务内容 系统字段设置 */
    sysFieldsSetting() {
      let serviceContentFields = this.taskFields.filter(
        (field) => field.formType == 'serviceContent'
      );
      let serviceTypeFields = this.taskFields.filter(
        (field) => field.formType == 'serviceType'
      );

      let serviceContentField = serviceContentFields[0] || {};
      let serviceTypeField = serviceTypeFields[0] || {};

      let isServiceContentFieldEnabled = serviceContentField.enabled == 1;
      let isServiceTypeFieldEnabled = serviceTypeField.enabled == 1;

      return {
        hasServiceContent: isServiceContentFieldEnabled,
        hasServiceType: isServiceTypeFieldEnabled,
      };
    },
    /** 工单类型列表 */
    taskTypeList() {
      return this?.initData?.taskTypeList || [];
    },
    /** 工单列表字段 */
    taskListFields() {
      let fixedFields = fields.slice();

      return []
        .concat(fixedFields)
        .filter((f) => f.formType !== 'separator' && f.formType !== 'info')
        .filter(item=>{
          if(item.fieldName == 'planTime') {
            return !this.isCalendar
          } else if(item.fieldName == 'planStartTime' || item.fieldName == 'planEndTime'){
            return this.isCalendar
          }
          return true 
        })
        .sort((a, b) => a.orderId - b.orderId);
    },
    /** 工单类型过滤后的字段 */
    taskTypeFilterFields() {
      let fields = this.taskFields.concat(this.taskReceiptFields) || [];
      let taskTypeFilterFields = fields.filter((field) => {
        return (
          LIST_FILTER_FORM_TYPE.indexOf(field.formType) == -1
          && field.isSystem == 0
        )
        // return field.isSystem == 0
      });
      return taskTypeFilterFields;
    },
    taskAllFields() {
      return this.taskFields.concat(this.taskReceiptFields)
    },
    /* 是否显示 批量创建/生成服务报告 */
    isShowBatchCreateOrPrintReport() {
      return (
        this.taskState === TaskStateEnum.FINISHED.value || this.showGuidangBtn
      )
    },
    /**
     * @desscription 是否允许删除工单
     * 1. 删除工单权限
    */
    allowDelete() {
      return AuthUtil.hasAuth(this.auth, AuthEnum.TASK_DELETE)
    },

    hasCallAuth() {
      return !!getRootWindow(window).CTI
    },
    // 标准版隐藏发送服务报告功能
    isShowBatchSendingServiceReports() {
      return this._isShowBatchSendingServiceReports
    },
    // 基础版功能隐藏服务报告
    isBasicEditionHideServiceReport() {
      return isBasicEditionHideServiceReport() 
    },
    // 基础版功能是否隐藏打印
    isBasicEditionHidePrintTask() {
      return isBasicEditionHidePrintTask() 
    },
    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct() 
    },
    // 基础版功能是否隐藏支付
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
    // 基础版功能是否隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent() 
    },
    // 基础版功能是否隐藏计划任务
    isBasicEditionHidePlanWork() {
      return isBasicEditionHidePlanWork() 
    },
    // 基础版功能是否隐藏api
    isBasicEditionHideApi() {
      return isBasicEditionHideApi() 
    },
    // 基础版功能是否隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart() 
    },
    // 基础版功能是否隐藏服务项目
    isBasicEditionHideServe() {
      return isBasicEditionHideServe() 
    },
    isLimitTenant() {
      return true
    },
    /** 
    * @description 是否开启云仓灰度
    */
    isCloudwarehouse() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskCloudWarehouse || false
    },
    /** 
    * @description 是否开启服务商灰度
    */
    isProviderManager() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.providerManager || false
    },
    /** 
    * @description 是否开启服务商子表单灰度
    */
    isServiceProviderSubForm() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.serviceProviderSubForm || false
    },
    /** 
    * @description 是否开启故障库灰度
    */
    isFaultGrayscale(){
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.faultLibrary
     },
    /**
     * @des 海伦哲灰度判断
     */
    isHandlerGray(){
      return this.allGrayInfo && this.allGrayInfo[GrayFunctionEnum.HANDLERGRAY]
    },
    // 是否是服务商
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false
    },
  },
  filters: {
    displaySelect(value) {
      if (!value) return null;
      if (value && typeof value === 'string') {
        return value;
      }
      if (Array.isArray(value) && value.length) {
        return value.join('，');
      }
      return null;
    },
    /** 审批状态 */
    displayApprove(value) {
      return value == 0 ? i18n.t('common.task.approveStatus.noApprove') : i18n.t('common.task.approveStatus.approve')
    },
    qualityStatus(value){
      if(!value) return ''
      return value == 'IN' ? i18n.t('common.task.qualityGuarantee.in') : i18n.t('common.task.qualityGuarantee.out')
    }
  },
  created(){
    this.findFastPageData(); // 页面加载选中传入数据
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.fasterPage'){
        // 接收条件数据 选中传入数据
        const {data:parseData, type} = data;
        if(type == `bbx-faster-${pageTaskList.type}`){
          this.findFastPageData(parseData); // 处理选中传入数据
          this.search(); // 查询数据
        }
      }

      // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
      if (action == 'shb.frame.activatedPage'){
        this.$nextTick(()=> {
          this.knowTableContainerHeight();
        })
      }
    });
    // 服务商灰度开启并且不是服务商人员，插入预置视图
    if(this.isProviderManager && !this.isProviderUser) {
      let providerTypes = [
        { name: i18n.t('task.list.serviceProviderCreate'), id: 'serviceProviderCreate' },
        { name: i18n.t('task.list.serviceProviderExecutor'), id: 'serviceProviderExecutor' },
      ]
      providerTypes.forEach(item=>{
        this.preViews.push({
          viewId: 'task_'+item.id,
          viewName: item.name,
          searchModel: [
            {
              fieldName: 'taskCommonSearch',
              value: {
                taskType: '',
                exceptionNodes: 'all',
                taskState: 'all',
                visualAngle: 'all',
                provideType: item.id
              },
              operator: ''
            }
          ],
          authEdit: false,
          visibleType: 1,
          module: 'task',
          isPre:true
        })
      })
    }
  },
  watch:{
    taskStates() {
      // 工单状态改变 计算折叠
      this.calcCollapse();
    },
    taskTypes() {
      // 工单类型改变 计算折叠
      this.calcCollapse();
    },
  },
  async mounted() {
    try {
      // 读取缓存 覆盖初始值
      await this.revertStorage();
    } catch (error) {
      console.error('revertStorage', error);
    }
    this.getTaskCost()

    try {
      const planTaskDataString = localStorage.getItem('plantask_task_list')
      const planTaskData = planTaskDataString ? JSON.parse(planTaskDataString) : {}
      if (planTaskData.columnStatus && !Array.isArray(planTaskData.columnStatus)) {
        localStorage.removeItem('plantask_task_list');
      }
      if (isObject(planTaskData)) {
        this.taskPage.pageSize = planTaskData?.pageSize || 10
      }

      // this.taskTypes = [...this.taskTypes, ...this.taskTypeList];
      // this.currentTaskType = this.taskTypeList.length === 1 ? this.taskTypes[1] : this.taskTypes[0];
    } catch(error) {
      console.error(error);
    }

    this.getTurnOnTaskExceptionNodeInfo()

    // this.search();
    
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        this.knowTableContainerHeight()
      }, 500)
    })


    // 页面初始化
    this.initialize()
    this.getSystemGrayInfo();

    /* 检查是否还有物流剩余次数 */
    this.checkQuota()

    window.addEventListener('resize', this.calcCollapse);
    this.$once('beforeDestroy', () => window.removeEventListener('resize', this.calcCollapse));
    
  },
  methods: {
    openConnectorDialog(column, row) {
      const value = row.attribute[column.field] || [];
      this.$refs.connectorDialogRef.open(column, value);
    },
    // 获取富文本内容
    openRichtextVisible(row, column){
      const richtextId = row.attribute[column.field] || ''
      if(!richtextId) return
      getRichTextContent({
        ids: [richtextId],
      })
        .then(res => {
          if (res.code == 0 || res.status == 0) {
            const richtextCon = res.result[0].content ?? '';
            this.richtextContent = richtextCon;
            this.richtextVisible = true;
          } else {
            throw res;
          }
        })
        .catch(err => {
          this.$notify.error({
            title: i18n.t('task.tip.errorTip'),
            message: err.message,
            duration: 2000,
          });
        })
    },
    getTaskCost(){
      TaskApi.getTaskCost().then(res=>{
        if(res.succ && res.data){
          this.isShowImportCost = true
        }
      })
    },

    formattedOpenDataTooltip(record = '') {
      return formattedOpenDataTooltip(record || '')
    },
    // 处理人员显示
    getUserName (value) {
      // 多选
      if (Array.isArray(value)) {
        return value.map((i) => i.displayName || i.name).join(',');
      }

      let user = value || {};
      return user.displayName || user.name;
    },
    getUserIds (value) {
      // 多选
      if (Array.isArray(value)) {
        return value.map((i) => i.staffId);
      }

      let user = value || {};
      return [user.staffId];
    },
    getRelationUserIds (value) {
      // 客户产品关联跟人有关的字段 返回的是字符串
      if(!value) return []
      return value.split(',') || [];
    },
    /** 工单列表拨打电话 */
    async makePhoneCall(phone, isLinkman) {
      if(!this.customerSetting.linkmanOn && isLinkman) return;
      try {
        ctiCallOut(phone) // taskType:'customer'
      } catch (error) {
        console.error(error);
      }
    },

    abnormalLabel(type) {
      if (!this.abnormalData.taskCustomExceptionNodeList?.length) return
      const list = this.abnormalData.taskCustomExceptionNodeList.map(item => {return item.exceptionName})
      if (list.indexOf(type) !== -1) return true
      return false
    },
    getFanWei(type){
      for(let i of this.abnormalData.taskExceptionRange){
        if(i.switch){
          if(type === i.chineseName ){
            return true
          }
        }
      }
      return false
    },
    abnormalHover(item) {
      if (!item) return
      const {overTime, isPaused, oncePaused, onceOverTime, state, onceRefused, onceReallot, onceRollback, positionException, currIsReallot, currIsRoback} = item
      const s = safeNewDate().getTime()
      const e = safeNewDate(overTime).getTime()

      let value = []
      // 超时
      if(overTime && this.abnormalLabel(i18n.t('common.task.exceptionStatus.overTime')) && s > e && this.getFanWei(this.taskStateEnum.getState(item.state))) {
        value.push(i18n.t('common.task.exceptionStatus.overTime'))
      }
      if (isPaused && this.abnormalLabel(i18n.t('common.task.exceptionStatus.pause'))) {
        value.push(i18n.t('common.task.exceptionStatus.pause'))
      }
      if (oncePaused && this.abnormalLabel(i18n.t('common.task.exceptionStatus.oncePaused'))) {
        value.push(i18n.t('common.task.exceptionStatus.oncePaused'))
      }
      if (onceOverTime && this.abnormalLabel(i18n.t('common.task.exceptionStatus.onceOverTime'))) {
        value.push(i18n.t('common.task.exceptionStatus.onceOverTime'))
      }
      if (state === 'refused' && this.abnormalLabel(i18n.t('common.task.exceptionStatus.refused'))) {
        value.push(i18n.t('common.task.exceptionStatus.refused'))
      }
      if (onceRefused && this.abnormalLabel(i18n.t('common.task.exceptionStatus.onceRefused'))) {
        value.push(i18n.t('common.task.exceptionStatus.onceRefused'))
      }
      if (currIsReallot && this.abnormalLabel(i18n.t('common.task.exceptionStatus.allot'))) {
        value.push(i18n.t('common.task.exceptionStatus.allot'))
      }
      if (currIsRoback && this.abnormalLabel(i18n.t('common.task.exceptionStatus.rollback'))) {
        value.push(i18n.t('common.task.exceptionStatus.rollback'))
      }
      if (onceReallot && this.abnormalLabel(i18n.t('common.task.exceptionStatus.onceAllot'))) {
        value.push(i18n.t('common.task.exceptionStatus.onceAllot'))
      }
      if (onceRollback && this.abnormalLabel(i18n.t('common.task.exceptionStatus.onceRollback'))) {
        value.push(i18n.t('common.task.exceptionStatus.onceRollback'))
      }
      if (state === 'offed' && this.abnormalLabel(i18n.t('common.task.exceptionStatus.offed'))) {
        value.push(i18n.t('common.task.exceptionStatus.offed'))
      }
      if (positionException && this.abnormalLabel(i18n.t('common.task.exceptionStatus.positionException'))) {
        value.push(i18n.t('common.task.exceptionStatus.positionException'))
      }

      return value

    },
    /** 异常选择 */
    checkAbnormal({englishName}){
      this.resetAdvancedConditions(); // 需求：切换快捷条件 高级搜索内保留条件但是搜索不携带
      this.exceptionNodes = englishName
      this.initPage()
      this.search()
    },
    // 获取异常节点多语言label
    getTaskExceptionStateLabel(name) {
      return TaskExceptionStateLabelEnum[name] || name
    },
    // 获取创建方式的多语言label
    getSoureceLabel(key) {
      return TaskCreateMethodLabelEnum[key] || key
    },
    /** 获取用户开启的配置节点 以及工单搜索范围 和 异常原因字段值 */
    async getTurnOnTaskExceptionNodeInfo() {
      const {success, result} = await TaskApi.getTurnOnTaskExceptionNodeInfo()
      if(success) {
        result.taskCustomExceptionNodeList.map(item => {
          item.exceptionName = this.getTaskExceptionStateLabel(item.exceptionName)
          return item
        })
        this.abnormalData = result
        this.abnormalData['hoverText'] = result.taskCustomExceptionNodeList.map(item => {return item.exceptionName}).join(',')
        this.taskCustomExceptionNodeList = [...this.taskCustomExceptionNodeList, ...result.taskCustomExceptionNodeList]

        const {taskExceptionReasonList} = result
        this.abnormals = this.abnormals.map((item, index) => {
          item.setting['isMulti'] = false
          taskExceptionReasonList.forEach(v => {
            if (item.englishName === v.englishName) {
              item.setting['dataSource'] = v.exceptionReason
            }
          })
          return item
        })
      }

    },
    nextStep() {
      this.nowGuideStep ++;
    },
    stopStep() {
      this.nowGuideStep = 5;
    },

    _number(number) {
      return number ? number : 0;
    },
    /**
     * @description 时间戳转换
     */
    timestamp(value) {
      if (typeof value === 'number') {
        let h = value / 3600 < 0 ? 0 : parseInt(value / 3600), m;
        if (h > 0) {
          m = (value % 3600) ? Math.ceil((value % 3600) / 60) : value % 3600
        } else {
          m = Math.ceil(value / 60)
        }

        if(m > 59) {
          m = 0;
          h ++;
        }
        return i18n.t('task.list.howManyHourAndMinute', {h, m});
      } 
      return ''
      
    },
    // 删除计划任务工单
    async deleteTask(obj) {
      const res = await this.$platform.confirm(i18n.t('task.tip.deleteTaskTip1'))
      if (!res) return;
      this.pending = true;
      const taskIds = [obj.planTaskId]
      const params = {
        planId: this.planId,
        taskIds,
      }
      TaskApi.deletePlanTaskTask(params).then(res => {
        if (res.success) {
          this.$platform.notification({
            title: this.$t('common.base.tip.deleteSuccess'),
            type: 'success'
          })
          this.search()
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error'
          });
          this.pending = false;
        }
      }).catch(err => {
        console.log(err);
        this.pending = false;
      })
    },
    // 立刻创建工单
    async createTaskNow(obj) {
      const res = await this.$platform.confirm(i18n.t('task.taskTypes.planTask.tips1'))
      if (!res) return;

      const params = {
        planId: obj.planId,
        taskId: obj.planTaskId
      }
      this.pending = true;
      TaskApi.createTaskNow(params).then(res => {
        if (res.success) {
          this.$platform.notification({
            title: this.$t('common.base.tip.createSuccess'),
            type: 'success'
          })
          this.search()
        } else {
          this.$platform.notification({
            title: res.message,
            type: 'error'
          });
          this.pending = false;
        }
      }).catch(err => {
        console.log(err);
        this.pending = false;
      })
    },
    // 调整工单创建时间
    changeCreateTime(row) {
      this.$refs.taskCreateTime.openDialog(row)
    },
    submitCreateTime() {
      this.search()
    },
    /**
     * @description 表头更改
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 构建 列表 + 选择列
     */
    async buildColumns() {
      const localStorageData = await this.getIndexedDbData();
      const {
        paymentConfig
      } = this.initData;

      let columnStatus = []
      const storageKey = this.getTaskListStorageKey();
      if(storageKey && localStorageData[storageKey]){
        columnStatus =localStorageData[storageKey]
      }else{
        columnStatus = localStorageData.columnStatus && localStorageData.columnStatus
      }

      if(!columnStatus) columnStatus = []

      let localColumns = columnStatus
        .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          }
          return acc
        }, {});
      let taskListFields = this.filterTaskListFields();
      let fields = taskListFields.concat(this.taskTypeFilterFields);

      // 如果没有服务商资质则去除列表和选择列的相关信息
      if(!this.isProviderManager){
        fields = fields
          .filter(item => item.formType !== 'serviceProviderQualification')
          .filter(item => item.formType !== 'engineerQualification')
      }
      if(fields.some(item => item.formType === 'relationForm')){
        // 过滤掉关联表单的相关内容
        fields = fields.filter(val => val.formType !== 'relationForm')
      }
      // 合并质保信息
      if(this.taskFields.filter(item=>item.formType==="quality").length){
        fields.forEach((item,index)=>{
          if(item.fieldName==='product'){
            fields.splice(index+1,0,qualityFields[0],qualityFields[1],qualityFields[2])
          }
        })
      }

      // 里程字段合并
      let Mileage = this.taskFields.filter(item=>['taskEstimatedMileage','estimatedMileage','actualMileage'].includes(item.formType))
      if(Mileage.length){
        Mileage.forEach((item,index)=>{
          item.templateId = undefined
          fields.push(item)
        })
      }

      fields = fields.concat(AbnormalList)
      
      // 故障库字段
      if(this.isFaultGrayscale) {
        fields = fields.concat(FaultLibrary)
      }

      fields = [...fields.filter(item=>!item.isCommon), ...this.commonFields].sort((a, b) => a.orderId - b.orderId);

      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns)
      }

      fields.push(
        {
          label: i18n.t('common.fields.action.displayName'),
          displayName: i18n.t('common.fields.action.displayName'),
          fieldName: 'btnArray',
          field: 'btnArray',
          conType: 'btnArray',
          fixed: 'right',
          isSystem: 1,
          tableName: 'task',
          // 操作列特殊判断 不能用选择列控制它的显示与隐藏 
          show: 'important'
        }

      )
      // E 高级搜索
      let columns = fields
        .filter(f => !['attachment', 'separator', 'info', 'autograph'].includes(f.formType))
        .filter(f => (f.isCommon === 1 || f.isSystem === 1) && f.tableName === 'task') // 只保留系统字段和公共字段
        .map((field) => {
          let sortable = false;
          let minWidth = 120;

          if (['date', 'datetime', 'number', 'planStartTime', 'planEndTime'].indexOf(field.formType) >= 0) {
            sortable = 'custom';
            minWidth = 100;
          }

          if (['address'].indexOf(field.formType) >= 0) {
            minWidth = 200;
          }

          if (['level', 'updateTime', 'createUserName', 'executorName', 'state'].indexOf(field.fieldName) >= 0) {
            sortable = 'custom';
          }

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (sortable && field.displayName.length >= 4) {
            minWidth = 125;
          }

          if (
            field.formType === 'datetime'
            || field.fieldName === 'updateTime'
            || field.fieldName === 'createTime'
          ) {
            minWidth = 160;
          }

          if (
            ['taddress', 'templateName'].indexOf(field.fieldName) >= 0
          ) {
            minWidth = 200;
          }

          if (['taskNo'].indexOf(field.fieldName) !== -1) {
            minWidth = 250;
            sortable = 'custom';
          }
          if (field.fieldName === 'customer') {
            sortable = 'custom';
            minWidth = 125;
          }
          if (field.fieldName === 'taskNo' || field.fieldName === 'btnArray') {
            field.width = 216
          }
          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
            fixed: field.fixed
          };
        })
        .map((col) => {
          let show = col.show === true;
          let { width } = col;
          let localField = localColumns[col.field]?.field || null;
          let fixLeft = localField?.fixLeft || null;

          if (null != localField) {
            if (localField.width) {
              width = typeof localField.width == 'number'
                ? `${localField.width}px`
                : localField.width;
            }
            show = localField.show !== false;
          } else {
            show = true;
          }
          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left'

          return col;
        });

      // 根据版本号判断是否需要支付方式
      if (!paymentConfig?.version) {
        columns = columns.filter((item) => {
          return item.fieldName !== 'paymentMethod';
        });
      }

      // 并本地缓存列数据至当前实例的列数据
      this.mergeLocalStorageColumnsToColumns(columns)

      this.columns = []
      this.$nextTick(() => {
        this.columns = columns;
      })
      return columns
    },
    /**
     * @description 合并本地缓存列数据至当前实例的列数据
     */
    async mergeLocalStorageColumnsToColumns(columns = []) {
      const { columnStatus } = await this.getIndexedDbData()
      if (isEmpty(columnStatus)) return

      mergeFieldsWithProperty(
        columns,
        columnStatus,
        (column, localStorageDataColumnItem) => {
          // 列名不匹配则返回
          if (getFieldName(column) !== getFieldName(localStorageDataColumnItem)) return
          // 覆盖列显示状态
          column.show = Boolean(localStorageDataColumnItem.show)
          // 覆盖宽度数据
          if (localStorageDataColumnItem?.width) {
            column.width = localStorageDataColumnItem.width
          }
        }
      )
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = []

      originFields.forEach(originField => {
        let {
          fieldName
        } = originField
        let field = fieldsMap[fieldName]

        if (field) {
          let {
            index
          } = field
          fields[index] = originField
        } else {
          unsortedFields.push(originField)
        }

      })

      return fields.concat(unsortedFields)
    },

    /**
     * @description 构建多行文本
     * @return {String}
     */
    buildTextarea(value) {
      return value
        ? value.replace(LINK_REG, (match) => {
          return `<a href="javascript:;" target="_blank" url="${match}">${match}</a>`;
        })
        : '';
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task',
        isFromSetting: false
      };
      return TaskApi.getAllFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    // 单独获取质保字段的相关信息
    getQualityField(){
      return TaskApi.getQualityFieldApi()
        .then(result => result?.data || [])
        .catch(() => [])
    },
    /**
     * @description 获取工单回执字段列表
     * @return {Promise}
     */
    fetchTaskReceiptFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task_receipt',
        isFromSetting: false
      };
      return TaskApi.getAllFields(params).then((result) => {
        result && result.forEach((field) => {
          field.group = 'task_receipt';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    /** 
     * @description 获取公共字段
    */
    getCommonFields(){
      let params = {
        tableName: 'all',
        typeId: this.currentTaskType.id || '',
      };
      return TaskApi.getCommonFields(params).then((result) => {
        result && result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },

    /**
     * @description 过滤工单列表字段
     * @return {Array<TaskField>} 过滤后工单列表字段
     */
    filterTaskListFields() {
      let fields = this.taskListFields || [];
      let field = null;

      let customerSetting = this.customerSetting;
      let sysFieldsSetting = this.sysFieldsSetting;

      let newFields = [];

      for (let i = 0; i < fields.length; i++) {
        field = fields[i];

        // 未开启联系人
        if (
          !customerSetting.linkmanOn
          && (field.fieldName == 'tlmName' || field.fieldName == 'tlmPhone')
        ) {
          continue;
        }

        // 未开启地址
        if (!customerSetting.addressOn && field.fieldName == 'taddress') {
          continue;
        }

        // 未开启产品
        if (!customerSetting.productOn && field.fieldName == 'product') {
          continue;
        }

        // 服务类型
        if (
          !sysFieldsSetting.hasServiceType
          && field.fieldName == 'serviceType'
        ) {
          continue;
        }

        // 服务内容
        if (
          !sysFieldsSetting.hasServiceContent
          && field.fieldName == 'serviceContent'
        ) {
          continue;
        }

        // 基础版过滤产品、支付方式、结算时间、关联事件、曾打印字段
        if (
          this.isBasicEditionHideProduct
          && field.fieldName === 'product'
        ) {
          continue;
        }
        if (
          this.isBasicEditionHidePay
          && (field.fieldName === 'paymentMethod' || field.fieldName === 'balanceTime')
        ) {
          continue;
        }
        if (
          this.isBasicEditionHideEvent
          && field.fieldName === 'eventNo'
        ) {
          continue;
        }
        if (
          this.isBasicEditionHidePrintTask
          && field.fieldName === 'oncePrinted'
        ) {
          continue;
        }
        // 未开启服务商子表单灰度 过滤掉服务商
        if (
          !this.isServiceProviderSubForm
          && field.fieldName === 'serviceProviders'
        ) {
          continue;
        }

        newFields.push(field);
      }

      return newFields;
    },
    /**
     * @description 格式化自定义地址
     * @param {Object} row 列表行数据
     * @param {Object} column 字段数据
     * @return {String} 过滤后的地址
     */
    formatCustomizeAddress(row, column) {
      const customizeAddress = column.isSystem ? row[column.formType] : row?.attribute[column.fieldName]
      if (null == customizeAddress) return '';

      return formatAddress(customizeAddress)
    },
    /**
     * @description 格式化服务团队
     */
    formatExecutorTags(executorTags) {
      if (null == executorTags) return '';
      
      return executorTags.map(item => item.name).join('、');
    },
    /**
     * @description 获取本地存储数据
     * @return {Object} 本地存取数据对象
     */
    getLocalStorageData() {
      const dataStr = storageGet(TASK_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },
    /**
     * @description 获取本地db数据
     */
    getTaskListStorageKey() {
      // 没有视图 使用计划任务id
      const planTask = 'planTaskAll'
      // 不要根据工单类型进行存储
      const taskTypeId = 'planTaskAll'

      return `${planTask}_${taskTypeId}`
    },
    async getIndexedDbData() {
      let data = {}
      let taskListStorageKey = this.getTaskListStorageKey()

      try {
        data = await StorageUtil.storageGet(taskListStorageKey, {}, StorageModuleEnum.PlanTask)
      } catch (error) {
        data = {}
        console.error('Caused ~ planTaskList ~ getIndexedDbData ~ error', error)
      }
      
      return data
    },
    /**
     * @description 获取行的key
     * @param {Object} row 行数据
     * @return {String} key
     */
    getRowKey(row = {}) {
      return `${row.iid}${(Math.random() * 1000) >> 2}`;
    },
    /**
     * @description 表格选择操作
     * @param {Array} selection 选择的数据
     */
    handleSelection(selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter((ms) =>
        this.taskPage.list.some((cs) => cs.id === ms.id)
      );

      let unSelected = this.taskPage.list.filter((c) =>
        original.every((oc) => oc.id !== c.id)
      );

      if (tv.length > MAXCHECK) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach((row) => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(i18n.t('common.base.tip.selectAtMostTip', {max: MAXCHECK}));
      }
      this.multipleSelection = tv;
      // this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    /**
     * @description 页大小改变操作
     * @param {Number} pageSize 页大小
     */
    handleSizeChange(pageSize) {
      this.saveDataToIndexedDb('pageSize', pageSize);
      this.initPage(1, pageSize);
      this.search();
    },
    /**
     * @description 初始化
     * @params isChangePage 初始化默认改变pageNum pageSize 批量编辑不改变
     */
    initialize(isChangePage = true, needSearch = true) {
      // 默认回到第一页 批量编辑保持当前页面
      this.loading = true;
      return Promise.all([this.fetchTaskFields(), this.fetchTaskReceiptFields(), this.getCommonFields()])
        .then(async (res) => {
          // 解析基础组件 物流组件字段
          this.$set(this, 'taskFields', smoothLogisticsField(res[0] || []));
          // 解析自定义字段 物流组件字段
          this.$set(this, 'taskReceiptFields', smoothLogisticsField(res[1] || []));
          // 解析公共字段 物流组件字段
          this.$set(this, 'taskCommonFields', smoothLogisticsField(res[2] || []))
          let arr1 = res[0].find((item) => {
            return item.fieldName === 'planTime';
          });
          let arr2 = res[0].find((item) => {
            return item.fieldName === 'planStartTime';
          })
          let arr3 = res[0].find((item) => {
            return item.fieldName === 'planEndTime';
          });
          this.planTimeType = arr1?.setting.dateType || '';
          this.planStartTimeType = arr2?.setting.dateType || '';
          this.planEndTimeType = arr3?.setting.dateType || '';
          // 当前选择的工单类型是全部
          if(!this.currentTaskType.id || this.currentTaskType.name === i18n.t('common.base.all')){
            const data = await this.getQualityField()
            this.taskFields = [ ...this.taskFields, ...data ]
          }
          this.buildColumns();
          if(needSearch) {
            isChangePage && this.initPage();
            this.search();
          } else {
            this.loading = false;
          }
        })
        .catch((err) => {
          this.loading = false;
          console.warn(err);
        });
    },
    /**
     * @description 初始化page
     */
    initPage(pageNum = 1, pageSize = this.taskPage.pageSize) {
      this.taskPage.pageNum = pageNum;
      this.taskPage.pageSize = pageSize;
    },
    /**
     * @description 初始化参数
     * @param {Number} pageSize 页大小
     * @returns {Object} params
     */
    initParams(pageSize = 10, keyword) {
      return {
        keyword,
        pageNum: 1,
        pageSize,
        orderDetail: {},
        moreConditions: {
          conditions: [],
        },
      };
    },
    /**
     * @description 页码跳转
     * @param {Number} pageNum 页码
     */
    jump(pageNum) {
      this.taskPage.pageNum = pageNum;
      this.search();
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc, {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage()
    },
    /**
     * @description 打开外部链接
     * @param {Object} e 事件对象
     */
    openOutsideLink(e) {
      let url = e.target.getAttribute('url');
      if (!url) return;
      if (!/http/gi.test(url))
        return this.$platform.alert(i18n.t('common.base.tip.outsideLinkTip'));

      this.$platform.openLink(url);
    },
    /**
     * @description 打开已选中列表面板
     */
    openSelectionPanel() {
      this.$refs.openSelectionPanel.open();
    },
    /**
     *
     * @description 打开客户详情
     * @param {object} clientInfo 客户详情
     */
    openClientTab(clientInfo) {
      const {
        linkAuth,
        customerEntity
      } = clientInfo;
      const {
        id
      } = customerEntity;
      if (!linkAuth) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
        fromId
      })
    },
    openEventTab(clientInfo){
      let id = clientInfo.eventId;
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: id
      })
    },  
    /**
     * @description 打开工单详情tab
     * @param {String} taskId 工单id
     */
    openTaskTab(taskId, taskNo) {
      if (!taskId) return;
      
      if (!this.globalIsHaveTaskViewDetailAuth) return

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: 'noHistory=1',
        fromId
      })
    },
    /**
     * @description 打开用户详情tab
     * @param {String} userId 用户id
     */
    openUserTab(userId) {
      if (!userId) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: userId,
        params: `noHistory=1&from=task`,
        fromId
      })
    },
    /**
     * @description 重置参数
     */
    resetParams() {
      this.taskState = 'all'; // 重置 工单状态
      // this.taskStates.forEach(item => item.checked = item.value === 'all')
      this.exceptionNodes = 'all'; // 重置 异常节点
      this.currentTaskType = this.taskTypes[0]; // 重置 工单类型
      this.provideType = ''; // 重置服务商类型
      this.initPage();
    },
    /**
     * @description 还原本地存储
     */
    async revertStorage() {
      const {
        pageSize,
        column_number
      } = await this.getIndexedDbData();
      const data = await this.getIndexedDbData();
      console.log('revertStorage', data)
      if(pageSize) {
        this.taskPage.pageSize = pageSize
      }
      if (column_number) this.columnNum = Number(column_number);
    },
    /**
     * @description 保存数据到本地存储
    */
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(TASK_LIST_KEY, JSON.stringify(data));
    },
    /**
     * @description 保存数据到本地indexedDB
    */
    async saveDataToIndexedDb(key, value) {
      const data = await this.getIndexedDbData()
      data[key] = value
      StorageUtil.storageSet(this.getTaskListStorageKey(), data, StorageModuleEnum.PlanTask);
    },
    /**
     * @description 派单方式文案
     */
    allotTypeText(params) {
      let text;
      switch (params) {
      case 1:
        text = i18n.t('task.detail.components.manualDispatch');
        break;
      case 2:
        text = i18n.t('task.detail.components.poolDispatch');
        break;
      case 3:
        text = i18n.t('task.detail.components.autoDispatch');
        break;
      default:
        text = '';
        break;
      }
      return text;
    },
    /* 异常搜索字段 */
    abnormalParams() {
      if (this.taskState === 'exception' && this.abnormalData.taskExceptionRange.length) {
        let exceptionStates = []
        this.abnormalData.taskExceptionRange.forEach(item => {
          if (item.switch) exceptionStates = [...exceptionStates, ...item.taskExceptionRangeValue]
        })
        let params = {
          exceptionNodes: this.exceptionNodes !== 'all' ? [this.exceptionNodes] : this.taskCustomExceptionNodeList.filter(item => {return item.englishName}).map(item => {return item.englishName}),
          isException: 1,
          exceptionStates
        }
        return params
      }
      return {}
    },

    // 获取子表单的字段
    getSubFormFieldList(fields, isReceipt) {
      let allSubFormList = []
      fields.forEach(item => {
        if(item?.setting?.isSubForm && (item.subFormFieldList && item.subFormFieldList.length > 0)) {
          let columns = item.subFormFieldList || []
          columns.forEach(sub => {
            sub.value = sub.fieldName
            sub.label = sub.displayName
            sub.field = sub.fieldName
            sub.export = true
          })

          allSubFormList.push({
            value: item.fieldName,
            label: isReceipt ? `${i18n.t('task.list.zhongqiText.receiptInfo')}：${item.displayName}` : item.displayName ,
            columns
          })
        }
      })
      return allSubFormList
    },

    /**
     * @description 已选择面板数据变化
     */
    selectionPanelInputChange(value) {
      this.multipleSelection = value.slice();
    },
    /**
     * @description 已选择面板移除某一项
     */
    selectionPanelRemoveItem({
      selection,
      item
    }) {
      selection.length < 1
        ? this.toggleSelection()
        : this.toggleSelection([item]);
    },
    /**
     * @description 计算已选择
     * @param {Array} selection 已选择列表
     * @return {Array} 计算过滤后的列表
     */
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter((ms) =>
        this.taskPage.list.every((c) => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    /**
     * @description 显示最后一次更新记录
     * @param {Object} row 行数据
     */
    showLatestUpdateRecord(row) {
      if (row.latesetUpdateRecord) return;

      TaskApi.getTaskUpdateRecord({
        taskId: row.id
      })
        .then((res) => {
          if (!res || res.status) return;

          this.taskPage.list.forEach((c) => {
            if (c.id === row.id) {
              this.$set(c, 'latesetUpdateRecord', res.data);
            }
          });
        })
        .catch((e) => console.error('e', e));
    },
    /**
     * @description 打开选择列设置
     */
    showColumnsSetting() {
      this.$refs.advanced.open(this.columns, this.currentTaskType);
    },
    /**
     * @description 排序变化
     * @param {Object} option 配置
     */
    sortChange(option) {
      const UserNameConvertMap = {
        'createUserName': 'createUser',
        'executorName': 'executorUser',
        'customer': 'customerName',
        'qualityStartTime': 'qualityStartTime',
        'qualityEndTime': 'qualityEndTime',
        'expectCreateTime': 'expectCreateTime',
      }

      try {
        let {
          prop,
          order
        } = option;

        if (!order) {
          this.sortModel = null;
          return this.search();
        }
        const sortedField = this.taskListFields.filter((sf) => sf.fieldName === prop)[0] || {};

        let isSystem = 0;
        let isConvertedProp = Object.keys(UserNameConvertMap).indexOf(prop) > -1

        if (prop === 'createTime' || prop === 'updateTime' || isConvertedProp) {
          isSystem = 1;
        } else {
          isSystem = sortedField.isSystem;
        }

        if (isConvertedProp) {
          prop = UserNameConvertMap[prop]
        }

        let sortModel = {
          isSystem,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          // column: isSystem ? `task.${prop}` : prop,
          column: prop,
        };

        if (
          prop === 'createTime'
          || prop === 'updateTime'
          || sortedField.formType === 'date'
          || sortedField.formType === 'datetime'
        ) {
          sortModel.type = 'date';
        } else if (prop === 'level' || prop === 'taskNo') {
          sortModel.type = 'string';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.sortModel = sortModel;
        this.initPage();
        this.search();
      } catch (e) {
        console.error('e', e);
      }
    },
    /**
     * @description 选择项切换
     * @param {Array<Row>} rows 行
     */
    toggleSelection(rows = []) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (Array.isArray(rows) && rows.length > 0) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.taskPage.list.every((item) => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || []
      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage()
        this.$message.success(i18n.t('common.base.saveSuccess'));
        // 把选中数据的选中状态再次渲染到表格上面去
        if (this.multipleSelection.length) {
          this.$nextTick(() => {
            this.multipleSelection.forEach(item => {
              this.taskPage.list.forEach(v => {
                if (v.id === item.id) {
                  this.$refs.multipleTable.toggleRowSelection(v, true);
                }
              })
            })
          })
        }
      })
    },
    async saveColumnStatusToStorage() {
      const localStorageData = await this.getIndexedDbData();
      let columnsStatus = null

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      const saveKey = this.getTaskListStorageKey()

      if(localStorageData[saveKey]){
        try{
          localStorageData[saveKey] = columnsList;
          columnsStatus = localStorageData[saveKey];
        }catch(err){
          console.error(err)
        }
      }else if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }
      if(saveKey){
        this.saveDataToIndexedDb(saveKey,columnsStatus)
      }else{
        this.saveDataToIndexedDb('columnStatus', columnsStatus); //默认选择列保存
      }
    },
    /** @return 人员userId和展示字段 */
    presonDisplayObj(attr, fieldName, row) {
      let obj = {};
      switch(fieldName) {
      case 'createUserName':
        obj = row.createUser;
        break;
      case 'executorName':
        obj = row.executorUser;
        break;
      case 'allotName':
        obj = row.allotUser;
        break;
      default:
        break;
      }
      
      obj = obj || {};
      
      return obj[attr];
    },
    /**
     * @des 查询是否有查询参数
     */
    findFastPageData(data){
      return new Promise((resolve, reject)=>{
        try {
          let parseData = sessionStorageGet(`bbx-faster-${pageTaskList.type}`);
          if(!data && !parseData) return resolve()
          sessionStorageRemove(`bbx-faster-${pageTaskList.type}`);
          // 解析参数
          const { filterData } = data || JSON.parse(parseData);
          const state = (filterData ? filterData.state : 'all').replace(/Id/g, '');
          if(state && this.taskStates.some(item => item.value === state)){
            // 传入state且在taskStateList中存在 选中此工单状态
            // chooseTaskState(this.taskStates.find(item => item.checked = item.value === state))
            this.taskState = state;
          }
          // this.fasterFilterList(filterData);
        } catch (error) {
          console.warn(error, 'findFastPageData error try catch');
          resolve()
        }
      })
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - 150;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },

    /**
     * @des 获取系统内的灰度
     */
    getSystemGrayInfo(){
      getAllGrayInfo().then(res=>{
        this.allGrayInfo = res;
      })
    },

    // 生成搜索条件
    buildSearchParams() {
      const { currentTaskType, taskPage, sortModel } = this;
      const searchParams = {
        planId: this.planId,
        page: taskPage.pageNum,
        pageSize: taskPage.pageSize,
        ...this.abnormalParams(), // 异常工单
      }

      // 排序
      if(sortModel){
        const { column, isSystem, sequence } = sortModel;
        searchParams.sorts = [{
          property: isSystem ? column : `attribute.${column}`,
          direction: sequence,
        }, ];
      } 

      return searchParams;
    },

    async search() {
      const params = this.buildSearchParams();
      try {
        this.loading = true;
        const result = await TaskApi.getPlanTaskTaskList(params);
        let isSuccess = result?.success === true;
        if (!isSuccess) {
          this.$platform.alert(result?.message);
          this.initPage();
          return;
        }

        let data = result?.result || {};
        let { list, total, createdTaskNumber, finishedTaskNumber, uncreatedTaskNumber } = data;
        this.createdTaskNumber = createdTaskNumber
        this.finishedTaskNumber = finishedTaskNumber
        this.uncreatedTaskNumber = uncreatedTaskNumber

        data['list'] = (list || []).map((item) => {
          if(item.task) {
            item.task.pending = false
            item.task.acceptUsedTime = this.timestamp(item.task.acceptUsedTime);
            item.task.taskUsedTime = this.timestamp(item.task.taskUsedTime);
            item.task.workUsedTime = this.timestamp(item.task.workUsedTime);
            item.task.taskResponseTime = this.timestamp(item.task.taskResponseTime);
            item.task.createToCompleteUsedTime = this.timestamp(item.task.createToCompleteUsedTime);
            if (item.task.planTime && this.planTimeType === 'date') {
              item.task.planTime = formatDate(safeNewDate(item.task.planTime), 'YYYY-MM-DD');
            }
            if (item.task.planStartTime && this.planStartTimeType === 'date') {
              item.task.planStartTime = formatDate(safeNewDate(item.task.planStartTime), 'YYYY-MM-DD');
            }
            if (item.task.planEndTime && this.planEndTimeType === 'date') {
              item.task.planEndTime = formatDate(safeNewDate(item.task.planEndTime), 'YYYY-MM-DD');
            }
          }
          
          if(item?.task?.qualityEntity) {
            if(item.task?.qualityEntity?.qualityStartTime) {
              item.task.qualityEntity.qualityStartTime = formatDate(safeNewDate(item.task.qualityEntity.qualityStartTime), 'YYYY-MM-DD');
            }
            if(item.task?.qualityEntity?.qualityEndTime) {
              item.task.qualityEntity.qualityEndTime = formatDate(safeNewDate(item.task.qualityEntity.qualityEndTime), 'YYYY-MM-DD');
            }
          }

          return {
            ...item.task,
            ...item,
          }
        });
        this.taskPage.merge(Page.as(data));
        this.taskPage['totalElements'] = total;
        this.taskPage.list = data?.list || []


        // 把选中的匹配出来
        if (this.multipleSelection.length) {
          this.$nextTick(() => {
            this.multipleSelection.forEach(item => {
              this.taskPage.list.forEach(v => {
                if (v.id === item.id) {
                  this.$refs.multipleTable.toggleRowSelection(v);
                }
              })
            })
          })
        }

      } catch (error) { 
        console.error('search', error);
        this.taskPage.list = [];
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 计算折叠
     */
    calcCollapse: debounce(function (){
      const {taskStateListRef: stateEl, taskTypeListRef: typeEl} = this.$refs
      if(stateEl) {
        // 工单状态 折叠计算
        const height = stateEl.offsetHeight;
        this.taskStateNeedCollapse = height > 40; // 工单状态是否需要折叠
        if(!this.taskStateNeedCollapse && this.taskStateCollapse) {
          // 如果不允许折叠且打开状态需要全部展示
          this.taskStateCollapse = false; // 工单状态展开
        }
      }
      
      if(typeEl) {
        // 工单类型 折叠计算
        const height = typeEl.offsetHeight;
        this.taskTypeNeedCollapse = height > 40; // 工单状态是否需要折叠
        if(!this.taskTypeNeedCollapse && this.taskTypeCollapse) {
          // 如果不允许折叠且打开状态需要全部展示
          this.taskTypeCollapse = false; // 工单类型展开
        }
      }
    }, 500),
    productSerialNumberFormat
  },
  components: {
    ConnectorTableDialog, // 连接器明细
    [TaskCreateTimeDialog.name]: TaskCreateTimeDialog
  },
};
